package com.tcpConnection;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class TcpServer {

    //运行时先启动客户端
    public static void main(String[] args) throws IOException {

        ServerSocket serverSocket = null;
        //等待客户端连接过来
        Socket socket = null;
        //读取客户端的消息
        InputStream is = null;
        //管道流
        ByteArrayOutputStream baos = null;

        try{

            serverSocket = new ServerSocket(9999);
            //不断接收每一次请求
            while (true) {
                socket = serverSocket.accept();
                is = socket.getInputStream();
                baos = new ByteArrayOutputStream();
                byte[] buffer = new byte[1024];
                int len;
                //边读边写
                while ((len = is.read(buffer)) != -1) {
                    //用字节数组输出流管道来来写出读取到的字节
                    baos.write(buffer, 0, len);
                }
                System.out.println(baos.toString());
            }

        } catch (IOException e) {
            e.printStackTrace();
        }finally {

            baos.close();
            is.close();
            socket.close();
            serverSocket.close();

        }
    }

}
